package com.example.douyin.controller;

import com.example.douyin.service.DouyinOpenService;
import com.example.douyin.vo.Content;
import com.example.douyin.vo.DouyinMessageBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: dangwen
 * @createDate: 2020/12/8
 */
@Slf4j
@Controller
public class DouyinMessageController {

    @Autowired
    private DouyinOpenService douyinOpenService;


    /**
     * 接入第一步：通过clientKey获取授权码code
     *
     * @param response
     */
    @GetMapping("/v1/douyin/open/oauth/code")
    @ResponseBody
    public void getOauthCode(HttpServletResponse response) {
        String url = "";
        try {
            url = douyinOpenService.buildUrl();
            log.info("douyin request url: {}", url);
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("douyin url redirect error, url:{}, exception={}", url, e);
        }
    }

    /**
     * 接入第二步：通过授权码code获取access_token和open_id
     *
     * @param request：由于需要从请求url中获取parameter，改接口就是用来在接入第一步sendRedirect后，提供给抖音的callBackUrl
     */
    @GetMapping("/v1/douyin/open/oauth/accesstoken")
    @ResponseBody
    public void getAccessToken(HttpServletRequest request) {
        douyinOpenService.getAccessToken(request);
    }

    /**
     * 接收由抖音企业号发送过来的用户消息
     * 返回challenge值
     *
     * @param body
     */
    @PostMapping("/v1/douyin/open/oauth/receive")
    @ResponseBody
    public Content receiveMessage(@RequestBody DouyinMessageBody body) {
        log.info("douyin request message body is: {}", body);
        return douyinOpenService.processReceivedMessage(body);
    }

    @PostMapping("/v1/douyin/open/oauth/unauthorize")
    @ResponseBody
    public Content unauthorize(@RequestBody DouyinMessageBody body){
        return douyinOpenService.unauthorize(body);
    }

}
